#!/usr/bin/env bash
set -e

export LC_ALL=C.UTF-8
LOG_FILE="/root/result.log"
cur_path=$(pwd)

echo "start to prepare robot it env"
chmod +x /root/repo/ci-repos/.common_scripts/common.sh
source /root/repo/ci-repos/.common_scripts/common.sh
set_gitee_hosts
prepare_git $1 $2
prepare_conan2 $3 $4
prepare_bingo
prepare_sdk

echo "start to robot it.........."
cd "${cur_path}" || die "无法进入目录: ${cur_path}"

# 执行命令并获取退出码
timeout 45m bingo test -mt -jit 2>&1 | tee "${LOG_FILE}"
exit_code=${PIPESTATUS[0]}

# # 检查命令执行状态
if [ "${exit_code}" -eq 124 ]; then
    die "MOCK IT任务超时(45分钟)"
elif [ "${exit_code}" -gt 0 ]; then
    die "MOCK IT任务失败，退出码: ${exit_code}"
else
    echo "MOCK IT任务成功"
fi

# 检查特定错误模式
FAIL=$(grep -a -cE '===>>>>[[:space:]]+测试:.*[[:space:]]+失败' "${LOG_FILE}" 2>/dev/null) || FAIL=0
if [ "${FAIL}" -gt 0 ]; then
    die "MOCK IT 测试失败，请查看详细日志"
fi

if grep -qE '[1-9][0-9]* failed' "${LOG_FILE}" 2>/dev/null || [[ "${FAILED_COUNT}" -gt 0 ]]; then
    die "MOCK IT用例不通过，存在失败用例，请查看详细日志"
fi
